Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters.
Given "pwwkew", the answer is "wke"

题目大意:找出给定字符串最长无重复字符的子串长度。例如"pwwkew", "wke",答案是3

题目难度:Medium

/**
 * Created by gzdaijie on 16/5/3
 * 遍历字符串,使用数组chars记录当前子串中某个字符ch出现的位置,默认为 -1
 * start记录当前子串的起点位置
 * 如果字符没有出现过,char[ch]记录位置,计算长度更新max
 * 如果出现过, 则将start->重复字符的这一段字符串的字符位置还原为 -1, 更新start
 * 返回 max
 */

public class Solution {
    public int lengthOfLongestSubstring(String s) {
        int[] chars = new int[256];
        for (int i = 0; i < 256; ++i) {
            chars[i] = -1;
        }

        int start, max;
        start = max = 0;
        for (int i = 0; i < s.length(); ++i) {
            char ch = s.charAt(i);
            if (chars[ch] == -1) {
                chars[ch] = i;
                max = Math.max(max, i - start + 1);
            } else {
                while (start < chars[ch] + 1) {
                    chars[s.charAt(start++)] = -1;
                }
                chars[ch] = i;
            }
        }
        return max;

    }
}
gzdaijie            updated 2016-05-03 16:41:22

results matching ""

    No results matching ""